const Promise = require('bluebird');
const schedule = require('node-schedule');

module.exports = function (storage, config) {
    let {modelsData: {Goodses, RemoveGoodses, sequelize}, search: {searchEnable, goodsesSearch}} = storage;

    let removeGoodses = function () {
        return sequelize.query("select * from Goodses where ((TIMESTAMPDIFF(DAY, DATE(created_at), DATE(NOW())) > dayLeft and dayLeft > 0) or (TIMESTAMPDIFF(DAY, DATE(created_at), DATE(NOW())) > 15 and order_by < 10000)) or couponEffectiveEndTime <= NOW() or status = 'Deactivated'", {
            type: sequelize.QueryTypes.SELECT
        }).then(function (goodses) {
            return Promise.mapSeries(goodses, function (goods) {
                goods.deleted_at = new Date();
                return Goodses.destroy({where: {id: goods.id}}).then(function () {
                    if (searchEnable) {
                        goodsesSearch.delete(goods.id);
                    }
                    return RemoveGoodses.create(goods);
                }).catch(function (err) {
                    if (err) {
                        console.error('\n', err.stack || err.message);
                    }
                    return {success: false};
                });
            });
        });
    }

    /**
     * 每天凌晨清空过期优惠劵
     */
    schedule.scheduleJob('0 0 0 * * *', removeGoodses);

    return {
        removeGoodses: removeGoodses
    };
};